<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入策略名称或描述进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            :disabled="listLoading"
            @click="handleAction('create', '添加')"
          >添加策略
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table v-loading="listLoading" :data="data" border fit highlight-current-row style="width: 100%">
          <el-table-column align="center" label="策略名称" prop="name" sortable="custom" min-width="150">
            <template slot-scope="scope">
              <el-tag :type="scope.row.is_active ? 'success' : 'info'">
                {{ scope.row.name }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- <el-table-column align="left" label="策略描述" prop="description" min-width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.description || '-' }}</span>
            </template>
          </el-table-column> -->

          <el-table-column align="center" label="适用状态" prop="applicable_states_names" min-width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="state in scope.row.applicable_states_names"
                :key="state"
                size="mini"
                style="margin: 2px;"
              >
                {{ state }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column align="center" label="发送方式" prop="send_type" sortable="custom" width="120">
            <template slot-scope="scope">
              <el-tag :type="sendTypeColor(scope.row.send_type)">
                {{ sendTypeText(scope.row.send_type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column align="center" label="提醒配置" prop="remind_config" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.remind_config && scope.row.remind_config.length">
                <div style="margin-bottom: 5px;">{{ scope.row.remind_config.length }}个提醒点</div>
                <div>
                  <el-tag
                    v-for="(config, index) in scope.row.remind_config.slice(0, 2)"
                    :key="index"
                    size="mini"
                    :type="reminderTargetColor(config.reminder_target)"
                    style="margin: 1px;"
                  >
                    {{ config.days }}天-{{ reminderTargetText(config.reminder_target) }}
                  </el-tag>
                  <el-tag v-if="scope.row.remind_config.length > 2" size="mini" type="info" style="margin: 1px;">
                    +{{ scope.row.remind_config.length - 2 }}个
                  </el-tag>
                </div>
              </div>
              <span v-else>未配置</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="状态" prop="is_active" sortable="custom" width="80">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.is_active"
                :disabled="listLoading"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>

          <el-table-column align="center" label="创建时间" prop="create_at" sortable="custom" width="150">
            <template slot-scope="scope">
              {{ formatDate(scope.row.create_at) }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="380">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleViewReminders(scope.row)">查看提醒</el-button>
              <el-button size="mini" type="info" @click="handleAction('test', scope.row)">测试</el-button>
              <el-button size="mini" type="primary" @click="handleAction('edit', scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-show="total>0"
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      append-to-body
      :title="title"
      :width="'70%'"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >

      <el-form ref="dataForm" :model="temp" label-position="left" label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="策略名称" prop="name" :rules="[{required: true, message: '请输入策略名称'}]">
              <el-input v-model="temp.name" placeholder="请输入策略名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送方式" prop="send_type" :rules="[{required: true, message: '请选择发送方式'}]">
              <el-select v-model="temp.send_type" placeholder="请选择发送方式" style="width: 100%">
                <el-option
                  v-for="option in sendTypeOptions"
                  :key="option[0]"
                  :label="option[1]"
                  :value="option[0]"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="策略描述">
          <el-input
            v-model="temp.description"
            type="textarea"
            placeholder="请输入策略描述"
            :rows="3"
          />
        </el-form-item>

        <el-form-item label="适用订单状态" prop="applicable_states" :rules="[{required: true, message: '请选择适用的订单状态'}]">
          <el-select
            ref="stateSelect"
            v-model="temp.applicable_states"
            multiple
            placeholder="请选择适用的订单状态"
            style="width: 100%"
            value-key="id"
            clearable
            filterable
          >
            <el-option
              v-for="state in orderStates"
              :key="state.id"
              :label="state.name"
              :value="state.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="提醒配置">
          <el-card shadow="never" style="margin-bottom: 10px;">
            <div slot="header" class="clearfix">
              <span>提醒时间点配置</span>
            </div>

            <div v-if="temp.remind_config && temp.remind_config.length === 0" style="text-align: center; color: #999; padding: 20px 0;">
              暂无提醒配置，点击下方"添加提醒点"开始配置
            </div>

            <div v-for="(item, index) in temp.remind_config" :key="index" style="border: 1px solid #eee; padding: 15px; margin-bottom: 10px; border-radius: 4px;">
              <!-- 第一行：天数和优先级，删除按钮 -->
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="天数" label-width="60px">
                    <el-input-number
                      v-model="item.days"
                      :min="0"
                      :max="365"
                      :step="1"
                      controls-position="right"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="优先级" label-width="60px">
                    <el-select v-model="item.priority" placeholder="选择优先级" style="width: 100%">
                      <el-option
                        v-for="option in priorityOptions"
                        :key="option[0]"
                        :label="option[1]"
                        :value="option[0]"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="提醒对象" label-width="60px">
                    <el-select v-model="item.reminder_target" placeholder="选择提醒对象" style="width: 100%">
                      <el-option
                        v-for="option in reminderTargetOptions"
                        :key="option[0]"
                        :label="option[1]"
                        :value="option[0]"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6" style="text-align: right;">
                  <el-button type="danger" icon="el-icon-delete" size="mini" style="margin-top: 5px;" @click="removeRemindItem(index)">删除</el-button>
                </el-col>
              </el-row>

              <!-- 第二行：标题 -->
              <el-row>
                <el-col :span="24">
                  <el-form-item label="标题" label-width="60px">
                    <el-input v-model="item.title" placeholder="如：3天跟进提醒 - 支持变量：{days} {order_name} {customer_name}" />
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第三行：内容 -->
              <el-row>
                <el-col :span="24">
                  <el-form-item label="内容" label-width="60px">
                    <div class="markdown-editor">
                      <div class="markdown-toolbar">
                        <el-button-group size="mini">
                          <el-button title="粗体" @click="insertMarkdown(index, '**', '**')">
                            <i class="el-icon-s-grid" /> B
                          </el-button>
                          <el-button title="斜体" @click="insertMarkdown(index, '*', '*')">
                            <i class="el-icon-refresh-left" /> I
                          </el-button>
                          <el-button title="链接" @click="insertMarkdown(index, '[', '](url)')">
                            <i class="el-icon-link" />
                          </el-button>
                          <el-button title="标题" @click="insertMarkdown(index, '### ', '')">
                            <i class="el-icon-menu" /> H
                          </el-button>
                          <el-button title="列表" @click="insertMarkdown(index, '- ', '')">
                            <i class="el-icon-s-unfold" />
                          </el-button>
                        </el-button-group>
                        <span class="markdown-tip">支持Markdown语法</span>
                      </div>
                      <el-input
                        :ref="'contentTextarea' + index"
                        v-model="item.content"
                        type="textarea"
                        placeholder="支持Markdown语法和变量：
{order_name} - 订单名称
{order_no} - 订单编号
{customer_name} - 客户名称
{current_state} - 当前状态
{days} - 天数

您可以修改上方的默认模板内容..."
                        :rows="6"
                        class="markdown-textarea"
                      />
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 添加提醒点按钮放在底部 -->
            <div style="text-align: center; padding-top: 10px; border-top: 1px dashed #ddd;">
              <el-button type="primary" style="width: 200px;" @click="addRemindItem">
                <i class="el-icon-plus" /> 添加提醒点
              </el-button>
            </div>
          </el-card>
        </el-form-item>

        <el-row v-if="temp.send_type === 'dingding' || temp.send_type === 'both'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="钉钉Webhook">
              <el-input
                v-model="temp.dingding_hook"
                placeholder="备用钉钉webhook地址，可选"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="额外@手机号">
              <el-input
                v-model="temp.dingding_at_mobiles"
                placeholder="多个手机号用逗号分隔"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="启用状态">
          <el-switch
            v-model="temp.is_active"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" :loading="editloading" @click="confirm">
          {{ action === 'delete' ? '确认删除' : '确 定' }}
        </el-button>
      </span>
    </el-dialog>

    <!-- 测试弹窗 -->
    <el-dialog
      append-to-body
      title="测试策略"
      :width="'50%'"
      :visible.sync="testDialogVisible"
      :close-on-click-modal="false"
    >

      <el-form :model="testForm" label-position="left" label-width="120px">
        <el-form-item label="测试订单ID">
          <el-input v-model="testForm.order_id" placeholder="请输入要测试的订单ID" />
        </el-form-item>
        <el-form-item label="测试说明">
          <el-alert
            title="测试说明"
            type="info"
            description="输入订单ID后点击测试，系统将模拟为该订单创建提醒记录（不会真正发送通知）"
            :closable="false"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="testDialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="testLoading" @click="executeTest">开始测试</el-button>
      </span>
    </el-dialog>

    <!-- 提醒列表弹窗 -->
    <el-dialog
      append-to-body
      :title="'查看提醒 - ' + currentPlanName"
      :width="'80%'"
      :visible.sync="reminderDialogVisible"
      :close-on-click-modal="false"
    >

      <div style="margin-bottom: 15px;">
        <el-row>
          <el-input
            v-model="reminderKwInput"
            placeholder="输入订单编号或客户名称进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleReminderSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleReminderSearch">搜索</el-button>
          </el-input>
          <el-button type="primary" class="el-icon-refresh" :disabled="reminderListLoading" @click="getReminderList">刷新</el-button>
        </el-row>
      </div>

      <el-table
        v-loading="reminderListLoading"
        :data="reminderData"
        border
        fit
        highlight-current-row
        style="width: 100%"
        @selection-change="handleReminderSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column align="center" label="订单信息" min-width="200">
          <template slot-scope="scope">
            <div>
              <div><strong>{{ scope.row.order_name || scope.row.order_no }}</strong></div>
              <div style="color: #999; font-size: 12px;">{{ scope.row.customer_name }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="提醒标题" prop="title" min-width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="关联工单" prop="related_ticket" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.related_ticket">
              <el-tag type="info" size="mini">工单 #{{ scope.row.related_ticket }}</el-tag>
            </span>
            <span v-else style="color: #999;">无</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="优先级" prop="priority" width="100">
          <template slot-scope="scope">
            <el-tag :type="priorityColor(scope.row.priority)" size="mini">
              {{ priorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag :type="reminderStatusColor(scope.row.status)" size="mini">
              {{ reminderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="是否处理" prop="is_processed" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_processed ? 'success' : 'warning'" size="mini">
              {{ scope.row.is_processed ? '已处理' : '未处理' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column align="center" label="提醒时间" prop="remind_time" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.remind_time) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="发送时间" prop="sent_at" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.sent_at) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="处理时间" prop="processed_at" width="150">
          <template slot-scope="scope">
            {{ formatDate(scope.row.processed_at) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="220">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 'pending'"
              size="mini"
              type="warning"
              :disabled="reminderListLoading"
              @click="handleReminderAction('send', scope.row)"
            >发送</el-button>
            <el-button
              v-if="!scope.row.is_processed"
              size="mini"
              type="success"
              :disabled="reminderListLoading"
              @click="handleReminderAction('process', scope.row)"
            >处理</el-button>
            <el-button size="mini" type="primary" @click="handleReminderAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleReminderAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-show="reminderTotal>0"
        background
        :current-page="reminderListQuery.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="reminderListQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="reminderTotal"
        style="margin-top: 15px;"
        @size-change="handleReminderSizeChange"
        @current-change="handleReminderPageChange"
      />

      <span slot="footer" class="dialog-footer">
        <el-button
          type="danger"
          class="el-icon-delete"
          :disabled="reminderListLoading || selectedReminders.length === 0"
          @click="handleBatchDelete"
        >
          批量删除 ({{ selectedReminders.length }})
        </el-button>
        <el-button @click="reminderDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 提醒编辑弹窗 -->
    <el-dialog
      append-to-body
      :title="reminderEditTitle"
      :width="'60%'"
      :visible.sync="reminderEditDialogVisible"
      :close-on-click-modal="false"
    >

      <el-form ref="reminderForm" :model="reminderTemp" label-position="left" label-width="120px">
        <el-form-item label="提醒标题" prop="title" :rules="[{required: true, message: '请输入提醒标题'}]">
          <el-input v-model="reminderTemp.title" placeholder="请输入提醒标题" />
        </el-form-item>

        <el-form-item label="提醒时间" prop="remind_time" :rules="[{required: true, message: '请选择提醒时间'}]">
          <el-date-picker
            v-model="reminderTemp.remind_time"
            type="datetime"
            placeholder="选择提醒时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="优先级" prop="priority" :rules="[{required: true, message: '请选择优先级'}]">
          <el-select v-model="reminderTemp.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option
              v-for="option in priorityOptions"
              :key="option[0]"
              :label="option[1]"
              :value="option[0]"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="提醒内容">
          <el-input
            v-model="reminderTemp.content"
            type="textarea"
            placeholder="请输入提醒内容"
            :rows="6"
          />
        </el-form-item>

        <el-form-item v-if="reminderAction === 'process'" label="处理备注">
          <el-input
            v-model="reminderTemp.process_note"
            type="textarea"
            placeholder="请输入处理备注"
            :rows="4"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="reminderEditDialogVisible = false">取 消</el-button>
        <el-button :type="reminderAction !== 'delete'?'primary':'danger'" :loading="reminderEditLoading" @click="confirmReminderAction">
          {{ reminderAction === 'delete' ? '确认删除' : reminderAction === 'process' ? '确认处理' : '确 定' }}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, GetOptions, TestPlan } from '@/api/crm/crmorderfollowplan'
import { Get as GetOrderStates } from '@/api/crm/crmorderstate'
import { Get as GetReminders, Put as PutReminder, Delete as DeleteReminder, ExecuteReminder } from '@/api/crm/crmorderfollowreminder'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Crmorderfollowplan',
  data() {
    return {
      data: [],
      orderStates: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      // pagination
      listQuery: {
        page: 1,
        pageSize: 20
      },
      total: 0,

      action: null,
      title: '',
      temp: {
        name: '',
        description: '',
        applicable_states: [],
        send_type: 'ticket',
        remind_config: [],
        dingding_hook: '',
        dingding_at_mobiles: '',
        is_active: true
      },
      width: '',
      innerDialogVisible: false,
      editloading: false,

      // 测试相关
      testDialogVisible: false,
      testLoading: false,
      testForm: {
        order_id: ''
      },
      currentTestPlan: null,

      // 选项数据
      sendTypeOptions: [],
      priorityOptions: [],
      applicableStatesOptions: [],
      // 提醒对象选项
      reminderTargetOptions: [
        ['state_manager', '状态负责人'],
        ['state_department_all', '状态部门所有人'],
        ['order_manager', '订单负责人']
      ],

      // 提醒列表相关
      reminderDialogVisible: false,
      reminderData: [],
      reminderListLoading: false,
      reminderKwInput: '',
      reminderListQuery: {
        page: 1,
        pageSize: 20
      },
      reminderTotal: 0,
      currentPlanId: null,
      currentPlanName: '',
      selectedReminders: [], // 选中的提醒记录

      // 提醒编辑相关
      reminderEditDialogVisible: false,
      reminderEditTitle: '',
      reminderAction: null,
      reminderEditLoading: false,
      reminderTemp: {
        id: null,
        title: '',
        remind_time: '',
        priority: 'normal',
        content: '',
        process_note: ''
      }
    }
  },

  created() {
    // 先设置默认选项，防止API调用失败时界面空白
    this.setDefaultOptions()
    this.getOptions()
    this.getList()
    this.getOrderStates()
  },
  methods: {
    resetTemp() {
      this.temp = {
        name: '',
        description: '',
        applicable_states: [],
        send_type: 'ticket',
        remind_config: [],
        dingding_hook: '',
        dingding_at_mobiles: '',
        is_active: true
      }
      // 确保关键字段都是响应式的
      this.$set(this.temp, 'remind_config', [])
      this.$set(this.temp, 'applicable_states', [])
    },

    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.listQuery.pageSize,
        page: this.listQuery.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.data = response.data.data
          this.total = response.data.total
          this.listLoading = false
        }).catch(error => {
          console.error('获取列表失败:', error)
          this.listLoading = false
        })
    },

    getOrderStates() {
      GetOrderStates(null, qs.stringify({
        pagesize: 1000,
        all: '1',
        page: 1
      }))
        .then(response => {
          this.orderStates = response.data.data
        }).catch(error => {
          console.error('获取订单状态失败:', error)
        })
    },

    getOptions() {
      // 先检查是否已有默认选项，避免重复设置
      if (this.sendTypeOptions.length === 0) {
        this.setDefaultOptions()
      }

      GetOptions()
        .then(response => {
          // 检查响应结构
          let options = null
          if (response && response.data) {
            if (response.data.success && response.data.data) {
              // 标准格式: {success: true, data: {...}}
              options = response.data.data
            } else if (response.data.send_type_choices) {
              // 直接格式: {send_type_choices: [...], ...}
              options = response.data
            } else {
              return // 使用默认选项
            }
          } else {
            return // 使用默认选项
          }

          // 发送方式选项 - 只有在获取到有效数据时才覆盖默认值
          if (options.send_type_choices && Array.isArray(options.send_type_choices)) {
            this.sendTypeOptions = options.send_type_choices
          }

          // 优先级选项
          if (options.priority_choices && Array.isArray(options.priority_choices)) {
            this.priorityOptions = options.priority_choices
          }

          // 适用状态选项 (作为orderStates的补充或替代)
          if (options.applicable_states_options && Array.isArray(options.applicable_states_options)) {
            this.applicableStatesOptions = options.applicable_states_options
            // 如果后端提供了状态选项，就使用后端的数据
            this.orderStates = options.applicable_states_options
          }
        }).catch(() => {
          // 确保有默认选项可用
          if (this.sendTypeOptions.length === 0) {
            this.setDefaultOptions()
          }
        })
    },

    setDefaultOptions() {
      // 默认发送方式选项
      this.sendTypeOptions = [
        ['dingding', '钉钉通知'],
        ['ticket', '创建工单'],
        ['both', '钉钉+工单']
      ]

      // 默认优先级选项
      this.priorityOptions = [
        ['low', '低'],
        ['normal', '普通'],
        ['high', '高'],
        ['urgent', '紧急']
      ]
    },

    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.title = '新增策略'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.title = `确认要删除策略"${row.name}"?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.title = `修改策略"${row.name}"`

          // 先重置表单数据
          this.resetTemp()

          // 然后设置具体的值
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined && key !== 'applicable_states') {
              this.temp[key] = row[key]
            }
          })
          this.temp.id = row.id

          // 确保 orderStates 已加载，如果没有则等待加载完成
          if (!this.orderStates || this.orderStates.length === 0) {
            // 等待状态加载完成后再处理
            this.waitForOrderStatesAndSetEdit(row)
            return
          }

          this.processEditData(row)
          break
        case 'test':
          this.currentTestPlan = row
          this.testForm.order_id = ''
          this.testDialogVisible = true
          break
      }
    },

    confirm() {
      if (this.action !== 'delete') {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) {
            this.$message.warning('请检查表单填写是否完整')
            return
          }

          // 验证提醒配置
          if (!this.temp.remind_config || this.temp.remind_config.length === 0) {
            this.$message.warning('请至少添加一个提醒配置')
            return
          }

          // 验证每个提醒配置的完整性
          for (let i = 0; i < this.temp.remind_config.length; i++) {
            const config = this.temp.remind_config[i]
            if (!config.title || config.title.trim() === '') {
              this.$message.warning(`第${i + 1}个提醒点的标题不能为空`)
              return
            }
            if (!config.content || config.content.trim() === '') {
              this.$message.warning(`第${i + 1}个提醒点的内容不能为空`)
              return
            }
            if (config.days === null || config.days === undefined || config.days < 0) {
              this.$message.warning(`第${i + 1}个提醒点的天数设置不正确`)
              return
            }
            if (!config.reminder_target) {
              this.$message.warning(`第${i + 1}个提醒点的提醒对象不能为空`)
              return
            }
          }

          this.submitForm()
        })
      } else {
        this.submitForm()
      }
    },

    submitForm() {
      const _data = JSON.parse(JSON.stringify(this.temp))
      this.editloading = true

      switch (this.action) {
        case 'create':
          Post(_data).then(response => {
            this.innerDialogVisible = false
            this.editloading = false
            this.getList()
            this.notify('添加成功')
          }).catch(error => {
            this.editloading = false
            const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
            this.$message.error('创建失败：' + errorMessage)
          })
          break
        case 'delete':
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.editloading = false
            this.getList()
            this.notify('删除成功')
          }).catch(error => {
            this.editloading = false
            const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
            this.$message.error('删除失败：' + errorMessage)
          })
          break
        case 'edit':
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.editloading = false
            this.getList()
            this.notify('更新成功')
          }).catch(error => {
            this.editloading = false
            const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
            this.$message.error('更新失败：' + errorMessage)
          })
          break
      }
    },

    handleStatusChange(row) {
      Put(row.id, { is_active: row.is_active }).then(() => {
        this.notify(row.is_active ? '已启用' : '已禁用')
      }).catch(() => {
        // 失败时回滚状态
        row.is_active = !row.is_active
      })
    },

    addRemindItem() {
      // 确保 remind_config 是数组
      if (!this.temp.remind_config) {
        this.temp.remind_config = []
      }

      // 根据已有提醒数量设置默认天数
      const defaultDays = this.temp.remind_config.length === 0 ? 3
        : this.temp.remind_config.length === 1 ? 7
          : this.temp.remind_config.length === 2 ? 15
            : this.temp.remind_config.length + 1

      this.temp.remind_config.push({
        days: defaultDays,
        title: `${defaultDays}天跟进提醒`,
        content: `**重要提醒**：订单 {order_name} 已进入 {current_state} 状态 ${defaultDays} 天，请及时跟进客户 {customer_name}。
        
### 需要处理的事项：
- 联系客户了解最新需求
- 更新订单进度状态
- 准备相关技术资料
- 确认交期和价格

**订单信息**：
- 订单编号：{order_no}
- 客户：{customer_name}
- 当前状态：{current_state}

请尽快处理此订单，如有问题请及时沟通。`,
        priority: 'normal',
        reminder_target: 'state_manager' // 默认为状态负责人
      })
    },

    removeRemindItem(index) {
      this.temp.remind_config.splice(index, 1)
    },

    insertMarkdown(index, before, after) {
      const textareaRef = this.$refs['contentTextarea' + index]
      if (textareaRef && textareaRef[0]) {
        const textarea = textareaRef[0].$el.querySelector('textarea')
        const start = textarea.selectionStart
        const end = textarea.selectionEnd
        const selectedText = textarea.value.substring(start, end)
        const beforeText = textarea.value.substring(0, start)
        const afterText = textarea.value.substring(end)

        const newText = beforeText + before + selectedText + after + afterText
        this.temp.remind_config[index].content = newText

        // 设置光标位置
        this.$nextTick(() => {
          const newStart = start + before.length
          const newEnd = newStart + selectedText.length
          textarea.setSelectionRange(newStart, newEnd)
          textarea.focus()
        })
      }
    },

    renderMarkdown(content) {
      if (!content) return ''

      // 简单的Markdown渲染器
      let html = content
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // 粗体
        .replace(/\*(.*?)\*/g, '<em>$1</em>') // 斜体
        .replace(/###\s(.*?)(\n|$)/g, '<h3>$1</h3>') // 三级标题
        .replace(/##\s(.*?)(\n|$)/g, '<h2>$1</h2>') // 二级标题
        .replace(/#\s(.*?)(\n|$)/g, '<h1>$1</h1>') // 一级标题
        .replace(/^\s*-\s(.*)$/gm, '<li>$1</li>') // 列表项
        .replace(/\[([^\]]*)\]\(([^)]*)\)/g, '<a href="$2" target="_blank">$1</a>') // 链接
        .replace(/\n/g, '<br>') // 换行

      // 处理列表 - 修复正则表达式兼容性问题
      if (html.includes('<li>') && html.includes('</li>')) {
        html = html.replace(/(<li>[\s\S]*?<\/li>)/g, '<ul>$1</ul>')
      }

      return html
    },

    executeTest() {
      if (!this.testForm.order_id) {
        this.$message.warning('请输入订单ID')
        return
      }

      this.testLoading = true
      TestPlan(this.currentTestPlan.id, {
        order_id: this.testForm.order_id
      }).then(response => {
        this.testLoading = false
        this.testDialogVisible = false
        this.$message.success('测试完成，请查看返回结果')
      }).catch(() => {
        this.testLoading = false
      })
    },

    sendTypeText(type) {
      // 优先从动态获取的选项中查找
      if (this.sendTypeOptions && this.sendTypeOptions.length > 0) {
        const option = this.sendTypeOptions.find(opt => opt[0] === type)
        if (option) return option[1]
      }

      // 如果没有找到，使用默认映射
      const map = {
        'dingding': '钉钉通知',
        'ticket': '创建工单',
        'both': '钉钉+工单'
      }
      return map[type] || type
    },

    sendTypeColor(type) {
      const map = {
        'dingding': 'warning',
        'ticket': 'success',
        'both': 'primary'
      }
      return map[type] || ''
    },

    formatDate(dateStr) {
      if (!dateStr) return '-'
      return new Date(dateStr).toLocaleString()
    },

    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },

    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },

    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.listQuery.page = val
      this.getList()
    },

    // 点击搜索
    handleSearch() {
      this.listQuery.page = 1
      this.getList()
    },

    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },

    waitForOrderStatesAndSetEdit(row) {
      // 如果订单状态还没加载完，等待一段时间后重试
      const maxRetries = 10
      let retryCount = 0

      const checkAndProcess = () => {
        if (this.orderStates && this.orderStates.length > 0) {
          this.processEditData(row)
        } else if (retryCount < maxRetries) {
          retryCount++
          setTimeout(checkAndProcess, 200)
        } else {
          this.$message.warning('订单状态加载失败，可能影响状态显示')
          this.processEditData(row) // 即使失败也要打开对话框
        }
      }

      checkAndProcess()
    },

    processEditData(row) {
      // 处理状态数据：列表数据中只有状态名称，需要根据名称查找ID
      let applicableStateIds = []

      // 方法1：检查是否有 applicable_states 字段（完整编辑数据）
      if (row.applicable_states && Array.isArray(row.applicable_states)) {
        applicableStateIds = row.applicable_states.map(state => {
          const id = typeof state === 'object' ? state.id : state
          return id
        })
      } else if (row.applicable_states_names && Array.isArray(row.applicable_states_names)) {
        // 方法2：根据状态名称查找ID（列表数据）
        applicableStateIds = row.applicable_states_names.map(stateName => {
          const stateObj = this.orderStates.find(state => state.name === stateName)
          if (stateObj) {
            return stateObj.id
          } else {
            return null
          }
        }).filter(id => id !== null) // 过滤掉空值
      }

      // 确保ID类型匹配
      if (applicableStateIds.length > 0 && this.orderStates.length > 0) {
        const firstStateId = this.orderStates[0].id
        applicableStateIds = applicableStateIds.map(id => {
          if (typeof firstStateId === 'number' && typeof id === 'string') {
            return parseInt(id, 10)
          } else if (typeof firstStateId === 'string' && typeof id === 'number') {
            return String(id)
          }
          return id
        })
      }

      // 验证ID是否存在
      const validIds = applicableStateIds.filter(id => {
        const exists = this.orderStates.some(state => state.id === id)
        return exists
      })

      applicableStateIds = validIds

      // 确保 remind_config 是数组
      if (!this.temp.remind_config || !Array.isArray(this.temp.remind_config)) {
        this.$set(this.temp, 'remind_config', row.remind_config || [])
      }

      // 先打开对话框
      this.innerDialogVisible = true

      // 等待DOM渲染完成后设置状态
      this.$nextTick(() => {
        setTimeout(() => {
          this.$set(this.temp, 'applicable_states', applicableStateIds)
        }, 300)
      })
    },

    // 提醒相关方法
    handleViewReminders(row) {
      this.currentPlanId = row.id
      this.currentPlanName = row.name
      this.reminderKwInput = ''
      this.reminderListQuery.page = 1
      this.selectedReminders = [] // 重置选择
      this.reminderDialogVisible = true
      this.getReminderList()
    },

    getReminderList() {
      this.reminderListLoading = true
      GetReminders(null, qs.stringify({
        plan_id: this.currentPlanId,
        kw: this.reminderKwInput,
        pagesize: this.reminderListQuery.pageSize,
        page: this.reminderListQuery.page
      }))
        .then(response => {
          this.reminderData = response.data.data
          this.reminderTotal = response.data.total
          this.reminderListLoading = false
        }).catch(error => {
          console.error('获取提醒列表失败:', error)
          this.reminderListLoading = false
        })
    },

    handleReminderSearch() {
      this.reminderListQuery.page = 1
      this.selectedReminders = [] // 重置选择
      this.getReminderList()
    },

    handleReminderSizeChange(val) {
      this.reminderListQuery.pageSize = val
      this.getReminderList()
    },

    handleReminderPageChange(val) {
      this.reminderListQuery.page = val
      this.getReminderList()
    },

    handleReminderAction(action, row) {
      this.reminderAction = action
      switch (action) {
        case 'edit':
          this.reminderEditTitle = `修改提醒 - ${row.title}`
          this.reminderTemp = {
            id: row.id,
            title: row.title,
            remind_time: row.remind_time,
            priority: row.priority,
            content: row.content || '',
            process_note: row.process_note || ''
          }
          this.reminderEditDialogVisible = true
          break
        case 'delete':
          this.reminderEditTitle = `确认删除提醒 - ${row.title}`
          this.reminderTemp = {
            id: row.id,
            title: row.title,
            remind_time: row.remind_time,
            priority: row.priority,
            content: row.content || '',
            process_note: row.process_note || ''
          }
          this.reminderEditDialogVisible = true
          break
        case 'process':
          this.reminderEditTitle = `处理提醒 - ${row.title}`
          this.reminderTemp = {
            id: row.id,
            title: row.title,
            remind_time: row.remind_time,
            priority: row.priority,
            content: row.content || '',
            process_note: row.process_note || ''
          }
          this.reminderEditDialogVisible = true
          break
        case 'send':
          this.sendReminder(row)
          break
      }
    },

    confirmReminderAction() {
      if (this.reminderAction === 'delete') {
        this.reminderEditLoading = true
        DeleteReminder(this.reminderTemp.id)
          .then(() => {
            this.reminderEditDialogVisible = false
            this.reminderEditLoading = false
            this.getReminderList()
            this.notify('删除成功')
          }).catch(error => {
            this.reminderEditLoading = false
            const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
            this.$message.error('删除失败：' + errorMessage)
          })
      } else if (this.reminderAction === 'edit' || this.reminderAction === 'process') {
        this.$refs.reminderForm.validate((valid) => {
          if (!valid) {
            this.$message.warning('请检查表单填写是否完整')
            return
          }

          this.reminderEditLoading = true

          // 如果是处理操作，需要添加处理相关字段
          const updateData = { ...this.reminderTemp }
          if (this.reminderAction === 'process') {
            updateData.is_processed = true
            updateData.processed_at = new Date().toISOString()
          }

          PutReminder(this.reminderTemp.id, updateData)
            .then(() => {
              this.reminderEditDialogVisible = false
              this.reminderEditLoading = false
              this.getReminderList()
              this.notify(this.reminderAction === 'process' ? '处理成功' : '修改成功')
            }).catch(error => {
              this.reminderEditLoading = false
              const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
              this.$message.error((this.reminderAction === 'process' ? '处理' : '修改') + '失败：' + errorMessage)
            })
        })
      }
    },

    sendReminder(row) {
      this.$confirm(`确认发送提醒"${row.title}"吗？`, '确认发送', {
        type: 'warning'
      }).then(() => {
        ExecuteReminder(row.id, {})
          .then(() => {
            this.getReminderList()
            this.notify('发送成功')
          }).catch(error => {
            const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
            this.$message.error('发送失败：' + errorMessage)
          })
      }).catch(() => {
        // 用户取消，不做任何操作
      })
    },

    priorityText(priority) {
      const option = this.priorityOptions.find(opt => opt[0] === priority)
      return option ? option[1] : priority
    },

    priorityColor(priority) {
      const map = {
        'low': 'info',
        'normal': '',
        'high': 'warning',
        'urgent': 'danger'
      }
      return map[priority] || ''
    },

    reminderStatusText(status) {
      const map = {
        'pending': '待提醒',
        'sent': '已发送',
        'processed': '已处理',
        'failed': '发送失败',
        'cancelled': '已取消'
      }
      return map[status] || status
    },

    reminderStatusColor(status) {
      const map = {
        'pending': 'warning',
        'sent': 'success',
        'processed': 'primary',
        'failed': 'danger',
        'cancelled': 'info'
      }
      return map[status] || ''
    },

    reminderTargetText(target) {
      const option = this.reminderTargetOptions.find(opt => opt[0] === target)
      return option ? option[1] : target
    },

    reminderTargetColor(target) {
      const map = {
        'state_manager': 'primary',
        'state_department_all': 'warning',
        'order_manager': 'success'
      }
      return map[target] || ''
    },

    // 批量选择相关方法
    handleReminderSelectionChange(selection) {
      this.selectedReminders = selection
    },

    handleBatchDelete() {
      if (this.selectedReminders.length === 0) {
        this.$message.warning('请先选择要删除的提醒记录')
        return
      }

      this.$confirm(`确认删除选中的 ${this.selectedReminders.length} 条提醒记录吗？`, '批量删除确认', {
        type: 'warning',
        confirmButtonText: '确认删除',
        cancelButtonText: '取消'
      }).then(() => {
        this.executeBatchDelete()
      }).catch(() => {
        // 用户取消，不做任何操作
      })
    },

    async executeBatchDelete() {
      this.reminderListLoading = true
      const totalCount = this.selectedReminders.length
      let successCount = 0
      let failedCount = 0
      const failedItems = []

      try {
        // 逐个删除，避免并发过多导致服务器压力
        for (let i = 0; i < this.selectedReminders.length; i++) {
          const reminder = this.selectedReminders[i]
          try {
            await DeleteReminder(reminder.id)
            successCount++

            // 显示删除进度
            if (totalCount > 5) {
              this.$message({
                message: `正在删除... (${i + 1}/${totalCount})`,
                type: 'info',
                duration: 1000
              })
            }
          } catch (error) {
            failedCount++
            failedItems.push({
              id: reminder.id,
              title: reminder.title,
              error: error.message || '删除失败'
            })
            console.error(`删除提醒 ${reminder.id} 失败:`, error)
          }
        }

        this.reminderListLoading = false

        // 显示删除结果
        if (failedCount === 0) {
          this.notify(`成功删除 ${successCount} 条提醒记录`)
        } else if (successCount === 0) {
          this.$message.error(`删除失败，共 ${failedCount} 条记录删除失败`)
        } else {
          this.$message.warning(`删除完成：成功 ${successCount} 条，失败 ${failedCount} 条`)

          // 如果有失败的记录，可以显示详细信息
          if (failedItems.length > 0 && failedItems.length <= 3) {
            const failedTitles = failedItems.map(item => item.title).join('、')
            setTimeout(() => {
              this.$message.error(`删除失败的提醒：${failedTitles}`)
            }, 1000)
          }
        }

        this.selectedReminders = []
        this.getReminderList()
      } catch (error) {
        this.reminderListLoading = false
        const errorMessage = (error.response && error.response.data && error.response.data.message) || error.message || '未知错误'
        this.$message.error('批量删除失败：' + errorMessage)
        this.getReminderList()
      }
    }
  }
}
</script>

<style scoped>
.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}

/* 确保数字输入框正常显示 */
.el-input-number {
  width: 100% !important;
}

.el-input-number .el-input__inner {
  text-align: left !important;
}

/* 提醒配置区域样式 */
.el-form-item {
  margin-bottom: 15px;
}

.el-form-item__label {
  line-height: 32px;
}

/* Markdown编辑器样式 */
.markdown-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
}

.markdown-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  border-radius: 4px 4px 0 0;
}

.markdown-tip {
  font-size: 12px;
  color: #909399;
}

.markdown-textarea {
  border: none !important;
}

.markdown-textarea .el-textarea__inner {
  border: none !important;
  border-radius: 0 !important;
  resize: vertical;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.5;
}

</style>
